package API;

import Util.MyKey;
import Util.SignEncrypt;
import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.util.encoders.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class KjSign {
    public static void main(String[] args) throws Exception {
        // 初始化工具类
        SignEncrypt signEncrypt = new SignEncrypt();

        // 加载密钥
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] publicKeyBytes = Base64.decode(MyKey.publicKeystr.getBytes());
        byte[] privateKeyBytes = Base64.decode(MyKey.privateKeystr.getBytes());
        PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));

        // 通知JSON数据
        String jsonData = "{\n" +
                "  \"merch_id\": \"\",\n" +
                "  \"out_trade_no\": \"\",\n" +
                "  \"out_trade_time\": \"\",\n" +
                "  \"sign_no\": \"\",\n" +
                "  \"sign\": \"\"\n" +
                "}";

        // 解析JSON
        JSONObject json = JSONObject.parseObject(jsonData);
        String merchId = json.getString("merch_id");
        String outTradeNo = json.getString("out_trade_no");
        String outTradeTime = json.getString("out_trade_time");
        String signNo = json.getString("sign_no");
        String sign = json.getString("sign");

        // 解密sign_no
        String decryptSignNo = signEncrypt.decrypt(signNo, privateKey);

        // 组装验签串
        String verifyStr = String.format(
                "merch_id=%s&out_trade_no=%s&out_trade_time=%s&sign_no=%s",
                merchId, outTradeNo, outTradeTime, decryptSignNo
        );

        // 执行验签并输出结果
        boolean result = signEncrypt.verify(verifyStr, sign, publicKey);
        System.out.println("验签结果: " + (result ? "成功" : "失败"));
    }
}
